package com.kuang.JSON;


import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

/**
 * Created by 郭浩 on 2020/9/24 21:32
 */
public class jsonTest2 {
    public static void main(String[] args) {
        //将前端接受得
        String user = "{\"username\":\"admin\",\"password\":\"admin\"}";
        String userList = "[{\"username\":\"admin\",\"password\":\"admin\"},{\"username\":\"admin2\",\"password\":\"admin2\"}]";

        Gson gson = new Gson();
        //将待转换得json字符串和转换需要得对象传入  转换成对象
        User user1 = gson.fromJson(user, User.class);
        System.out.println(user1);

        //获得转换得对象
        JsonElement parse = new JsonParser().parse(userList);
        //转换成array
        JsonArray asJsonArray = parse.getAsJsonArray();
        for (int i = 0; i < asJsonArray.size(); i++) {
            JsonElement jsonElement = asJsonArray.get(i);
            User user2 = gson.fromJson(jsonElement, User.class);
            System.out.println(user2);
        }

    }
}
